define(function(require, exports, module) {

	var $ = require('jquery');
	require('spin/1.3/spin.js');
	require('jbox');
	require('artTemplate/artTemplate/2.0.1/template.js');
	require('jquery/jquery-form/1.0.0/jquery.form.js');
	require('jquery/jquery-json/2.4.0/jquery.json.js');
	require('jquery/jquery-validation/1.11.0/jquery.validate');
	require('jquery/jquery-validation/1.11.0/messages_zh');
	require('jquery/jquery-timeago/1.3.0/jquery.timeago.js');
	require('../header-page.js');
	var util = require('../util');
	var List = require('../util/list');

	exports.options = {
		listLink : '',
		listParams : '',
		pageLink : '',
		pageParams : ''
	};

	uid = $g_user.id;
	var fid = '';
	var date = '';
	var s = "10";

	// 验证
	$("#lerterForm").validate({
		rules : {
			content : {
				required : true
			},
		}
	});
	var status = "3";
	if ($g_user.role == 'instution') {
		status = "0";
	} else if ($g_user.role == 'charitarian') {
		status = "2";
	} else if ($g_user.role == 'user') {
		status = "3";
	} else {
		status = "3";
	}

	// 时间戳转换成日期
	exports.getLocalTime = function(t, callback) {
		var now = new Date(parseInt(t));// 转化long型日期为时间对象
		var year = now.getFullYear();
		var month = now.getMonth() + 1;
		var date = now.getDate();
		var hour = now.getHours();
		var minute = now.getMinutes();
		var second = now.getSeconds();
		var newDate = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
		return newDate;
	};

	exports.format = function(e) {
		$("#" + e + " .me_comment_msg").each(function() {
			var t = parseInt($(this).text());
			t = $.timeago(exports.getLocalTime(t));
			$(this).text(t);
		});
	};
	// tab动态渲染
	var msgTab = new List();
	msgTab.options.template = "msgTab-template";
	msgTab.options.container = "#msgTab";
	msgTab.options.links = {
		"list" : $CONFIG.base_url + '/api/user/count'
	};
	msgTab.options.params = {
		"uid" : uid,
		"status" : status
	};
	msgTab.load(function() {
		$("#messagebtn").on("click", function() {
			$(this).text("系统通知");
			exports.message();
		});
		$("#letterbtn").on("click", function() {
			exports.letter();
		});
		$("#commentToMebtn").on("click", function() {
			$(this).text("评论我的");
			exports.commentToMe();
		});
		$("#meCommentbtn").on("click", function() {
			$(this).text("我评论的");
			exports.commentToMe();
		});
		$("#couponbtn").on("click", function() {
			exports.coupon();
		});
		$("#giftbtn").on("click", function() {
			$(this).text("我的礼品");
			exports.giftComment();
		});
		//页面跳转定位
		var path = window.location.href;
		path = path.substr(path.lastIndexOf("#") + 1);
		if(path == "panel-coupon"){
			$("#couponbtn").click();
		}
	});

	// 删除评论
	exports.deComment = function deComment(callback) {
		var inforId = $.parseJSON($(this).attr("data")).id;
		exports.del("/api/comment/del", inforId, function() {
			$("#meCommentbtn").click();
		});
		callback();
	};

	/*
	 * 封装获取接口的方法 exports.loadData = function(modal,target,url,callback) { var
	 * listData = new List(); listData.options.template = modal;
	 * listData.options.container = target; listData.options.links = { "list" :
	 * $CONFIG.base_url + url }; listData.options.params = { "id" : uid, "p" :
	 * "1", "s" : s }; listData.load(function(data) {
	 * if(typeof("callback")=="function"){ callback(data); } }); };
	 */

	// 我评论的
	exports.meComment = function() {
		var meComment = new List();
		meComment.options.template = "panel-505741-table-template";
		meComment.options.container = "#panel-505741-table";
		meComment.options.links = {
			"list" : $CONFIG.base_url + '/api/comment/mycomment'
		};
		meComment.options.params = {
			"uid" : uid,
			"p" : "1",
			"s" : s
		};
		meComment.load(function() {
			exports.format("panel-505741-table");
		});

		/*
		 * exports.loadData("panel-505741-table-template","#panel-505741-table","/api/comment/user/list",function(){
		 * exports.format("panel-505741-table"); });
		 */

		$("#panel-505741-table").on("click", ".del_to_list", function() {
			exports.deComment.call(this);
			meComment.load();
		});
	};
	exports.meComment();
	// 我收到的礼品
	exports.giftComment = function() {
		var giftComment = new List();
		giftComment.options.template = "panel-505742-table-template";
		giftComment.options.container = "#panel-gift-count";
		giftComment.options.links = {
			"list" : $CONFIG.base_url + '/api/project/support/present/list'
		};
		giftComment.options.params = {
			"uid" : uid
		};
		giftComment.load(function() {
			$("#panel-gift-count .me_comment_msg").each(function() {
				var t = $(this).text();
				$(this).text($.timeago(t));
			});

		});

	};
	exports.giftComment();
	
	// 分配城市联动
	exports.getCityTypeSelect = function(parent, type, callback) {
		$.get($CONFIG.base_url + "/api/region/list/parent", {
			parentId : parent
		}, function(data) {
			var i, len = data.length, html = '';
			for (i = 0; i < len; i++) {
				if (i == "0") {
					html += '<option value="' + data[i].id + '" selected>' + data[i].name + '</option>';
					tasktype = data[i].id;
					$("#region-" + type + "-id").val(data[i].id);
				} else {
					html += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
				}
			}
			$("#region-" + type + "-select").empty().append(html);
			switch (type) {
			case "province":
				exports.getCityTypeSelect(tasktype, "city");
				break;
			case "city":
				exports.getCityTypeSelect(tasktype, "county");
				break;
			default:
				break;
			}
			if (typeof (callback) == "function") {
				callback(data);
			}

		});
	};

	// 评论我的
	exports.commentToMe = function() {
		var commentToMe = new List();
		commentToMe.options.template = "panel-205570-table-template";
		commentToMe.options.container = "#panel-205570-table";
		commentToMe.options.links = {
			"list" : $CONFIG.base_url + '/api/comment/to/list'
		};
		commentToMe.options.params = {
			"id" : uid,
			"p" : "1",
			"s" : s
		};
		commentToMe.load(function() {
			exports.format("panel-205570-table");
		});
	};
	$("#panel-205570-table").on('click', '.del_to_list', function() {
		var inforId = $.parseJSON($(this).attr("data")).id;
		exports.del("/api/comment/del", inforId, function() {
			$("#commentToMe").click();
		});
	});
	/*
	 * $("#panel-205570-table").on('click','#showComDia',function(){
	 * alert("查看对话"); });
	 */
	// 私信
	exports.letter = function() {
		var letter = new List();
		letter.options.template = "panel-205571-table-template";
		letter.options.container = "#panel-205571-table";
		letter.options.links = {
			"list" : $CONFIG.base_url + '/api/letter/contacter'
		};
		letter.options.params = {
			"uid" : uid,
			"p" : "1",
			"s" : s
		};
		letter.load(function() {
			$("#panel-205571-table .me_comment_msg").each(function() {
				var t = $(this).text();
				$(this).text($.timeago(t));
			});
		});
	};

	// 优惠券
	exports.coupon = function() {
		var coupon = new List();
		coupon.options.template = "coupon-template";
		coupon.options.container = "#panel-coupon-count";
		coupon.options.links = {
			"list" : $CONFIG.base_url + '/api/project/income/list/unusedcoupons'
		};
		coupon.options.params = {
			"uid" : uid,
			"p" : "1",
			"s" : s
		};
		coupon.load(function() {
			$("#couponsel").val(1);
			// console.log("d");
			$(".coupontime").each(function() {
				var t = $(this).text();
				exports.getLocalTime(t);
				$(".couponstatus").each(function() {
					var st = $(this).text();
					if (st == 0) {
						$(this).text("未使用");
					};
					$(".cou-label").each(function() {
						var val = $(this).text();
						if (val == "goods") {
							$(this).text("实物券");
						} else if (val == "money") {
							$(this).text("现金券");
						} else if (val == "activity") {
							$(this).text("虚拟券");

						}
					});

				});
			});

			// 优惠券列表选择
			$(".pull-right").change(function() {
				var val = $(".pull-right").find('option:selected').val();
				exports.uncoupon(val);
			});

		});

	};
	exports.uncoupon = function() {
		var uncoupon = new List();
		uncoupon.options.template = "coupon-template";
		uncoupon.options.container = "#panel-coupon-count";
		uncoupon.options.links = {
			"list" : $CONFIG.base_url + '/api/project/income/list/usedcoupons'
		};
		uncoupon.options.params = {
			"uid" : uid,
			"p" : "1",
			"s" : s
		};
		uncoupon.load(function() {
			$("#couponsel").val(2);
			// console.log("d");
			$(".coupontime").each(function() {
				var t = $(this).text();
				exports.getLocalTime(t);
				$(".operate").remove();
				$(".couponstatus").each(function() {
					var st = $(this).text();
					if (st ==1) {
						$(this).text("已使用");
					} else if (st ==2) {
						$(this).text("已失效");
					}
					;
					$(".cou-label").each(function() {
						var val = $(this).text();
						if (val == "goods") {
							$(this).text("实物券");
						} else if (val == "money") {
							$(this).text("现金券");
						} else if (val == "activity") {
							$(this).text("虚拟券");

						}
					});
				});
			});
			// 优惠券列表选择
			$(".pull-right").change(function() {
				var val = $(".pull-right").find('option:selected').val();
				exports.coupon(val);
			});

		});

	};

	// 领取现金券
	$(".message-content").on("click", ".money-btn", function() {
		var data = $.parseJSON($(this).attr("data"));
		var id = data.id;
		$.get($CONFIG.base_url + "/api/project/income/coupon/get", {
			"uid" : uid,
			"id" : id,
			"addressId" : "1"
		}).done(function(data) {
			if (data == true) {
				jBox.tip("金额已经转入雅米宝");
				exports.coupon();
			}
		}).fail(function() {
			jBox.tip("领取失败");
		});
	});
	// 领取实物券
	$(".message-content").on("click", ".goods-btn", function() {
		var data = $.parseJSON($(this).attr("data"));
		var id = data.id;
		$("#conaddress").on("click", ".conadd-sure", function(e, callback) {
			e.preventDefault();
			var data = $.parseJSON($(".addradio").attr("data"));
			var addressId = data.addressId;
			$.get($CONFIG.base_url + "/api/project/income/coupon/get", {
				"uid" : uid,
				"id" : id,
				"addressId" : addressId
			}).done(function(data) {
				if (data == true) {
					jBox.tip("领取实物券成功");
					exports.coupon();
					$("#con-add").modal("hide");
				}
			}).fail(function() {
				jBox.tip("领取实物券失败");
			});

		});
	});
	// 领取虚拟券
	$(".message-content").on("click", ".activity-btn", function() {
		var data = $.parseJSON($(this).attr("data"));
		var id = data.id;
		$.get($CONFIG.base_url + "/api/project/income/coupon/get", {
			"uid" : uid,
			"id" : id,
			"addressId" : "1"
		}).done(function(data) {
			if (data == true) {
				jBox.tip("领取成功，短信已发送至您的手机，请注意查收");
				exports.coupon();
			}
		}).fail(function() {
			jBox.tip("领取失败");
		});
	});

	// 发私信
	$("#panel-205571-table").on('click', '.chart', function() {
		fid = $(this).attr("data");
		if ($("#chart_diag").length) {
			$("#chart_diag").remove();
			// exports.addChart.call(this);
		} else {
			$("#chart_diag").remove();
			exports.addChart.call(this, uid, fid);
			$(".send_leter").click(function() {
				$this = $("#lerterForm");
				if (!$this.valid()) {
					return;
				}
				exports.submitForm(lerterForm, '/api/letter/send',function(){
					$("#letterbtn").click();
				});
				
			});
		}
	});

	// 站内信系统通知
	exports.message = function() {
		var letterStation = new List();
		letterStation.options.template = "systemInfor-template";
		letterStation.options.container = "#systemInfor";
		letterStation.options.links = {
			"list" : $CONFIG.base_url + '/api/message/list'
		};
		letterStation.options.params = {
			"uid" : uid,
			"p" : "1",
			"s" : "5"
		};
		letterStation.load(function() {
			$("#systemInfor table .msg_time").each(function() {
				var t = $(this).text();
				$(this).text($.timeago(t));
			});
		});
		// 删除
		$("#systemInfor").on('click', '.chart', function(e) {
			var inforId = $.parseJSON($(this).attr("data")).id;
			exports.del("/api/message/del", inforId, function() {
				letterStation.load();
			});
		});
	};

	// 优惠券地址列表
	exports.consendTo = function consendTo() {
		var consendTo = new List();
		consendTo.options.template = "conaddress-template";
		consendTo.options.container = "#conaddress";
		consendTo.options.links = {
			"list" : $CONFIG.base_url + '/api/user/sendto/list'
		};
		consendTo.options.params = {
			"uid" : uid
		};
		consendTo.load(function() {
			$(".default-address").each(function() {
				var st = $(this).text();
				if (st == 1) {
					$(this).text("默认地址");
					$(this).siblings().attr("checked", true);
				} else if (st == 0) {
					$(this).text("");
				}
			});

		});
	};
	$("#panel-coupon-count").on("click", ".goods-btn", function() {
		exports.consendTo();
	});

	// 展示对话框发私信
	$("#showDialogue").on('click', '.message_operation', function() {
		fid = $(this).attr("data");
		if ($("#chart_diag").length) {
			$("#chart_diag").remove();
			// exports.addChart.call(this);

		} else {
			$("#chart_diag").remove();
			exports.addChart.call(this, uid, fid);
			$(".send_leter").click(function() {
				$this = $("#lerterForm");
				if (!$this.valid()) {
					return;
				}
				exports.submitForm(lerterForm, '/api/letter/send',function(){});
			});
		}
	});

	// 弹出私信输入框
	exports.addChart = function addChart(uid, fid) {
		$(this)
				.parent()
				.after(
						"<div id='chart_diag' class='chart_diag'><form id='lerterForm' method=post'><input type='hidden' name='userId' value='"
								+ uid
								+ "'/><input type='hidden' name='friendId' value='"
								+ fid
								+ "'/><textarea rows='' cols='' name='content' class='form-control required'></textarea><a class='send_leter color_theme'>发送</a></form></div>");
	};
	exports.addChart2 = function addChart2(uid, fid) {
		$(this)
				.parent()
				.parent()
				.after(
						"<tr><td colspan='4'><div id='chart_diag' class='chart_diag' style='width:478px;'><form id='lerterForm' method=post'><input type='hidden' name='userId' value='"
								+ uid
								+ "'/><input type='hidden' name='friendId' value='"
								+ fid
								+ "'/><textarea rows='' cols='' name='content' class='form-control required'></textarea><a class='send_leter color_theme'>发送</a></form></div></td></tr>");
	};

	// 点击"回复",如果此时私信输入框存在，那么删除该私信输入框对应的tr元素;否则添加私信输入框
	$("#showDialogue").on('click', '.chart', function() {
		if ($("#chart_diag").length == 0) {
			commendTo = $(this).attr("data");
			var fid = $(this).attr("data");
			$("#chart_diag").remove();
			exports.addChart2.call(this, uid, fid, commendTo);
			$(".send_leter").click(function() {
				$this = $("#lerterForm");
				if (!$this.valid()) {
					return;
				}
				exports.submitForm(lerterForm, '/api/letter/send',function(){

				});
			});
		} else {
			$("#chart_diag").parent().parent().remove();
		}

	});
	// 定时器
	var secs = "1";
	exports.auto_jump = function auto_jump() {
		secs = secs - 1;
		if (secs < 0) {
			return false;
		}
		if (secs == 0) {
			clearInterval(time);
			$(".letter_send_seccuss").hide();
		}
	};
	// 提交表单
	exports.submitForm = function submitForm(e, v,callback) {
		var json = form2js(e, '.', true);
		var postData = $.toJSON(json);
		//console.log(postData);
		$.ajax({
			url : $CONFIG.base_url + v,
			type : "POST",
			data : postData,
			dataType : "json",
			contentType : "application/json",
			success : function(data) {
				$(".letter_send_seccuss").show();
				secs = "1";
				time = setInterval(exports.auto_jump, 1000);
				$("#chart_diag").remove();
				if(typeof(callback) == "function")
					callback();
			},
			error : function() {
				$.jBox.tip("亲，您发的内容太多了！");
			}
		});
	};
	// 删除系统通知
	exports.del = function(url, s, callback) {
		var gorp = (url == "/api/user/sendto/del") ? "GET" : "POST";
		$.jBox("确认删除？", {
			title : "友情提示",
			buttons : {
				"确定" : 1,
				"取消" : -1
			},
			submit : function(v, h, f) {
				if (v == "1") {
					$.ajax({
						url : $CONFIG.base_url + url,
						type : gorp,
						data : {
							"id" : s
						},
						dataType : "json",
						// contentType : "application/json",
						success : function(data) {
							//console.log(data);
							$.jBox.tip("删除成功！");
							if (typeof (callback) == "function") {
								callback();
							}
							;
							$.jBox.close(true);
						},
						error : function() {
							$.jBox.tip("删除失败！");
						}
					});

					return true;
				}
				if (v == "-1") {
					$.jBox.close();
					return false;
				}
			}
		});
	};
	$("#message-li-tabs1").click(function() {

		util.change('message-li-tabs1');
		util.rechange('message-li-tabs2');
	});

	$("#message-li-tabs2").click(function() {
		util.change('message-li-tabs2');
		util.rechange('message-li-tabs1');
	});
$("#showDialogue").on("click", "#show_more_letter", function() {
		var data = $.parseJSON($(this).attr("data"));
		var uid = data.uid;
		var fid = data.fid;
		var dateLong = $("#input-date").val();
		var nextPage = data.nextPage;
		var pageSize = data.pageSize;
		// 下载更多对话前，将当前对话内容保存起来
		var html = $("#showDialogue .more-detail").nextAll("div[class='row-fluid']");
		var showChart = new List();
		showChart.options.template = "showDialogue-template";
		showChart.options.container = "#showDialogue";
		showChart.options.links = {
			"list" : $CONFIG.base_url + "/api/letter/list/old"
		};
		showChart.options.params = {
			"uid" : uid,
			"p" : nextPage,
			"s" : pageSize,
			"date" : dateLong,
			"fid" : fid
		};
		showChart.load(function() {
			$(".time_stamp").each(function() {
				var t = $(this).text();
				$(this).text($.timeago(t));
			});
			$("#showDialogue").append(html);
		});
	});

	// 展示对话信息

	exports.showDiaPages = function showDiaPages(e, v, d, f,callback) {
		var showChart = new List();
		showChart.options.template = e + "-template";
		showChart.options.container = "#" + e;
		showChart.options.links = {
			"list" : $CONFIG.base_url + v
		};
		showChart.options.params = {"uid" : uid,"p" : "1","s" : "5","date":d,"fid" : f};
		showChart.load(function() {
			$(".time_stamp").each(function() {
				var t = $(this).text();
				$(this).text($.timeago(t));
			});
			if(typeof(callback) == "function")
				callback();
		});
	};
	
	// 私信 查看对话
	$("#panel-205571-table").on("click", ".show_Dialogue", function(e) {
		var data = $.parseJSON($(this).attr("data"));
		var sid = data.sid;
		$("#input-date").val(new Date().getTime());
		var dateStamp = e.timeStamp;
		exports.showDiaPages('showDialogue', '/api/letter/list/old', dateStamp, sid,function(){
			$("#letterbtn").text("私信");
		});
	});


});
